package com.cet;

import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

public class NIODemo {

    public static void main(String[] args) throws InterruptedException {
        nioA();
//        a();
    }

    public static void a() throws InterruptedException {
        System.out.println("invoke method a");
        String bResult = b("a param");
        System.out.println("result: " + bResult);
    }

    /**
     * 模拟一个远程调用耗时操作
     *
     * @param param
     * @return
     * @throws InterruptedException
     */
    public static String b(String param) throws InterruptedException {
        System.out.println("invoke method b, blocked 2 seconds!");
        TimeUnit.SECONDS.sleep(2);
        return "b response";
    }

    public static void nioA() {
        System.out.println("invoke method nioA");
        nioB("a param", NIODemo::callbackA);
        System.out.println("immediately finish!");
    }

    public static void callbackA(String param) {
        System.out.println("invoke callback method!");
        System.out.println(param);
    }

    public static void nioB(String param, Consumer<String> callback) {
        System.out.println("invoke method  noiB, no block!");
        new Thread(() -> {
            String result;
            try {
                result = b(param);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            callback.accept(result);
        }).start();
    }

}
